﻿using UnityEngine;

namespace GameToolkit
{
    [CreateAssetMenu(fileName = "InputActionDescriptor", menuName = "角色控制/动作输入描述")]
    public class InputActionDescriptor : InputDescriptor
    {
        [Header("From GameInput")]
        [SerializeField, GameInput]
        string m_InputName;

        [Header("From Computer")]
        [SerializeField, Range(0.01f, 1f)]
        float m_Threshold = 0.1f;

        GameInput.IInput mInput;

        public override ActorBehaviour.IInputAction Create(bool fromGameInput)
        {
            if (fromGameInput)
            {
                if (mInput == null)
                    mInput = GameInput.GetInput(m_InputName, GameInput.ECreateInputType.None);
#if UNITY_EDITOR
                if (mInput == null)
                    Debug.LogWarning($"The input({m_InputName}) is not exists.", this);
#endif
                return new ActionFromGinput(mInput);
            }
            else
            {
                return new ActionFromDesc(this);
            }
        }

        class ActionFromGinput : ActorBehaviour.IInputAction
        {
            GameInput.IInput mInput;
            public ActionFromGinput(GameInput.IInput input)
            {
                mInput = input;
            }

            public bool IsHolding => mInput != null && mInput.HasButton;
        
        }

        class ActionFromDesc : IConfigurableInputAction<float>
        {
            InputActionDescriptor mDesc;
            float mHoldValue;
            public ActionFromDesc(InputActionDescriptor desc)
            {
                mDesc = desc;
            }

            public bool IsHolding => mHoldValue >= mDesc.m_Threshold;

            public float GetInputValue()
            {
                return mHoldValue;
            }

            public void SetValue(float isHolding)
            {
                mHoldValue = isHolding;
            }
        }
    }
}
